package com.magist.manage.copyrights.controller;

import com.github.pagehelper.PageInfo;
import com.magist.core.controller.BaseController;
import com.magist.core.entity.CxtHolder;
import com.magist.core.entity.Page;
import com.magist.core.entity.ResultMessage;
import com.magist.core.enums.UserTypeEnum;
import com.magist.core.exception.BusinessException;
import com.magist.core.util.BeanCopyUtil;
import com.magist.core.util.DateUtil;
import com.magist.core.util.ExcelUtil;
import com.magist.manage.copyrights.dto.ContractRightsDto;
import com.magist.manage.copyrights.entity.ContractRights;
import com.magist.manage.copyrights.entity.Copyrights;
import com.magist.manage.copyrights.entity.SupplyContract;
import com.magist.manage.copyrights.export.ContractRightsExportDto;
import com.magist.manage.copyrights.importExcel.ContractRightsImportDto;
import com.magist.manage.copyrights.service.ContractRightsService;
import com.magist.manage.copyrights.service.CopyrightsService;
import com.magist.manage.copyrights.service.SupplyContractService;
import com.magist.manage.web.entity.UserInfo;
import com.magist.manage.web.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(value="合同授权信息接口",tags={"合同授权信息接口"})
@RestController
@RequestMapping("/rest/contractRights")
public class RestContractRightsController extends BaseController {

	@Autowired
	private ContractRightsService contractRightsService;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private CopyrightsService copyrightsService;
	@Autowired
	private SupplyContractService supplyContractService;

//	@AddLogAnnotation(opType = "ContractRights",simpleOpContent = "授权新增",identify = "contractRightsNo")
	@ApiOperation(value="保存", notes="保存接口")
	@RequestMapping(value = "save.do", method = RequestMethod.POST)
	public Object save(@ModelAttribute("contractRightsDto") ContractRightsDto contractRightsDto) {
		contractRightsService.addContractRights(contractRightsDto);
		return ResultMessage.success();
	}

	@ApiOperation(value="更新", notes="更新接口")
	@RequestMapping(value = "update.do", method = RequestMethod.POST)
	public Object update(@ModelAttribute("contractRightsDto") ContractRightsDto contractRightsDto) {
		ContractRights oldContractRights = contractRightsService.getById(contractRightsDto.getId());
		if(oldContractRights==null)
			throw new BusinessException("无效的数据!");
		ResultMessage result =null;
		String statis = oldContractRights.getStatis();
		if (contractRightsService.updateContractRights(contractRightsDto)>0)
			result = ResultMessage.success("操作成功");
		else
			result=ResultMessage.error("操作失败!");
		return result;
	}

	@ApiOperation(value="列表", notes="分页查询接口")
	@RequestMapping(value = "page.do", method = RequestMethod.GET)
	public Object page(@ModelAttribute("contractRightsDto")  ContractRightsDto contractRightsDto) {
		ResultMessage result = ResultMessage.success();
		UserInfo userInfo = userInfoService.getById(CxtHolder.getUser().getUserId());
		if (UserTypeEnum.OP.getCode().equals(userInfo.getUserType())) {
			contractRightsDto.setCreateById(userInfo.getId());
		}
		PageInfo<ContractRightsDto> pageInfo = contractRightsService.pageDto(contractRightsDto,getPageInfo());

		List<ContractRightsDto> list = pageInfo.getList();
//		 修改人&过期状态set
		if (!CollectionUtils.isEmpty(list)) {
			ArrayList<ContractRightsDto> contractRightsDtos = new ArrayList<>();
			for (ContractRightsDto contractRights : list) {


				Date now = new Date();
				Date endDate = contractRights.getEndDate();
				String expireStatus = null;
				int monthDiff = DateUtil.getMonthDiff( endDate,now);
				if (monthDiff == 0) {
					expireStatus = "1个月内到期";
				} else if (monthDiff > 0 && monthDiff < 3) {
					expireStatus = "3个月内到期";
				} else if (monthDiff >= 3 && monthDiff < 6) {
					expireStatus = "6个月内到期";
				} else if (monthDiff >= 6) {
					expireStatus = "6个月以外到期";
				}
				if (now.after(endDate)) {
					expireStatus = "已到期";
				}
				contractRights.setExpireStatus(expireStatus);
			}
		}

		result.setContent(pageInfo);
		return result;
	}

	@ApiOperation(value="删除", notes="删除接口")
	@RequestMapping(value = "del.do", method = RequestMethod.POST)
	public Object del(@ModelAttribute("id") String id) {
		ContractRights contractRights = contractRightsService.getById(id);
		if(contractRights==null)
			throw new BusinessException("无效的数据!");
		ResultMessage result =null;
		if(contractRightsService.delete(contractRights)>0)
			result = ResultMessage.success("操作成功");
		else
			result=ResultMessage.error("操作失败!");
		return result;
	}

	@ApiOperation(value="详情", notes="详情接口")
	@RequestMapping(value = "info.do", method = RequestMethod.GET)
	public Object info(@ModelAttribute("id") String id,String opt) {
		ContractRights contractRights = contractRightsService.getById(id);
		if(contractRights==null)
			throw new BusinessException("无效的数据!");
		ContractRightsDto contractRightsDto = new ContractRightsDto();
		BeanUtils.copyProperties(contractRights,contractRightsDto);
		// 作品信息,查看详情才需要查询
		if ("info".equals(opt)) {
			String copyrightId = contractRights.getCopyrightId();
			Copyrights copyrights = copyrightsService.getById(copyrightId);
			if (!ObjectUtils.isEmpty(copyrights)) {
				contractRightsDto.setWorksName(copyrights.getWorksName());
				contractRightsDto.setWorksType(copyrights.getWorksType());
				contractRightsDto.setIsbnNo(copyrights.getIsbnNo());
				contractRightsDto.setPublishingName(copyrights.getPublishingName());
				contractRightsDto.setAuthorName(copyrights.getAuthorName());
				contractRightsDto.setPublicationDate(copyrights.getPublicationDate());
				contractRightsDto.setWorksType(copyrights.getWorksType());
				contractRightsDto.setAnchorName(copyrights.getAnchorName());
				contractRightsDto.setSeriesNum(copyrights.getSeriesNum());
				contractRightsDto.setWorksPrice(copyrights.getWorksPrice());
				contractRightsDto.setWorksIntroduction(copyrights.getWorksIntroduction());
				contractRightsDto.setBackground(copyrights.getBackground());
				contractRightsDto.setRemark(copyrights.getRemark());
			}

			String contractNo = contractRights.getContractNo();
			SupplyContract supplyContract = supplyContractService.findByContractNo(contractNo);
			if (!ObjectUtils.isEmpty(supplyContract)) {
				contractRightsDto.setCertNo(supplyContract.getCertNo());
				contractRightsDto.setAccountName(supplyContract.getAccountName());
				contractRightsDto.setBankName(supplyContract.getBankName());
				contractRightsDto.setBankNo(supplyContract.getBankNo());
			}
		}

		ResultMessage result = ResultMessage.success();
		result.setContent(contractRightsDto);
		return result;
	}

	private Example packExample(Example example,ContractRightsDto contractRightsDto){
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("deleted","F");
		if(StringUtils.isNotEmpty(contractRightsDto.getId()))
			criteria.andEqualTo("id",contractRightsDto.getId());

		// 到期状态
		String expireStatus = contractRightsDto.getExpireStatus();
		if (StringUtils.isNotEmpty(expireStatus)) {
			Date now = new Date();
			if (expireStatus.equals("0")) {
				criteria.andLessThanOrEqualTo("endDate", now);
			} else if (Integer.valueOf(expireStatus) > 6) {
				criteria.andGreaterThanOrEqualTo("endDate", DateUtil.addMonths(now, 6));
			} else {
				criteria.andBetween("endDate", now, DateUtil.addMonths(now, Integer.valueOf(contractRightsDto.getExpireStatus())));
			}
		}
		// 结算形式
		if (StringUtils.isNotEmpty(contractRightsDto.getBalanceType()))
			criteria.andEqualTo("balanceType", contractRightsDto.getBalanceType());
		if (StringUtils.isNotEmpty(contractRightsDto.getSoleFlag()))
			criteria.andEqualTo("soleFlag", contractRightsDto.getSoleFlag());
		if (StringUtils.isNotEmpty(contractRightsDto.getSubRightsFlag()))
			criteria.andEqualTo("subRightsFlag", contractRightsDto.getSubRightsFlag());
		if (StringUtils.isNotEmpty(contractRightsDto.getStatis()))
			criteria.andEqualTo("statis", contractRightsDto.getStatis());

		// 名称/出版社/合同编号/版权号

		String compoundSearch = contractRightsDto.getCompoundSearch();
		if(!StringUtils.isEmpty(compoundSearch)) {
			Example.Criteria criteria2 = example.createCriteria();
//			criteria2.orLike("worksName", "%"+compoundSearch+"%");
//			criteria2.orLike("publishingName", "%"+compoundSearch+"%");
			criteria2.orLike("contractNo", "%"+compoundSearch+"%");
			criteria2.orLike("copyrightsNo", "%"+compoundSearch+"%");
			criteria2.orLike("contractRightsNo", "%"+compoundSearch+"%");
			example.and(criteria2);
		}

		// 授权范围
		String copyrightsRange = contractRightsDto.getCopyrightsRange();

		if (!StringUtils.isEmpty(copyrightsRange)) {
			Example.Criteria criteria4 = example.createCriteria();
			String[] ranges = copyrightsRange.split(",");
			for (String range : ranges) {
				criteria4.orLike("copyrightsRange", "%" + range + "%");
			}
			example.and(criteria4);
		}
		return example;
	}

	@ApiOperation(value = "失效授权", notes = "失效授权")
	@RequestMapping(value = "invalidContractRights.do", method = RequestMethod.POST)
	public Object invalidContractRights(@ModelAttribute("id") String id) {
		ContractRights contractRights = contractRightsService.getById(id);
		if (contractRights == null)
			throw new BusinessException("无效的数据!");
		ResultMessage result = null;
		if (contractRightsService.doInvalidContractRights(id) > 0)
			result = ResultMessage.success("操作成功");
		else
			result = ResultMessage.error("操作失败!");
		return result;
	}


	@ApiOperation(value = "批量失效授权", notes = "批量失效授权")
	@RequestMapping(value = "batchInvalid.do", method = RequestMethod.POST)
	public Object batchInvalid(@ModelAttribute("invalidIds") String invalidIds) {
		if(StringUtils.isEmpty(invalidIds)) {
			throw new BusinessException("未选择失效数据");
		}
		String[] invalids = invalidIds.split(",");
		ResultMessage result = null;
		for (String id : invalids) {
			ContractRights contractRights = contractRightsService.getById(id);
			if (contractRights == null)
				throw new BusinessException("无效的数据!");

			if (contractRightsService.doInvalidContractRights(id) > 0)
				result = ResultMessage.success("操作成功");
			else {
				result = ResultMessage.error("操作失败!");
				return result;
			}
		}
		return result;
	}




	@ApiOperation(value="通过合同编码查询合同授权列表", notes="通过合同编码查询合同授权列表")
	@RequestMapping(value = "fetchContractRightsList.do", method = RequestMethod.POST)
	public Object fetchContractRightsList(@ModelAttribute("contractNo") String contractNo) {
		ResultMessage result = ResultMessage.success();
		if(StringUtils.isEmpty(contractNo)) {
			return result;
		}
		ContractRights entity = new ContractRights();
		entity.setContractNo(contractNo);

		// 修改人&过期状态set
		List<ContractRights> list = contractRightsService.find(entity);
		if (!CollectionUtils.isEmpty(list)) {
			ArrayList<ContractRightsDto> contractRightsDtos = new ArrayList<>();
			for (ContractRights contractRights : list) {
				ContractRightsDto contractRightsDto1 = BeanCopyUtil.copy(contractRights, ContractRightsDto.class);

				Date now = new Date();
				Date endDate = contractRights.getEndDate();
				String expireStatus = null;
				int monthDiff = DateUtil.getMonthDiff( endDate,now);
				if (monthDiff == 0) {
					expireStatus = "1个月内到期";
				} else if (monthDiff > 0 && monthDiff < 3) {
					expireStatus = "3个月内到期";
				} else if (monthDiff >= 3 && monthDiff < 6) {
					expireStatus = "6个月内到期";
				} else if (monthDiff >= 6) {
					expireStatus = "6个月以外到期";
				}
				if (now.after(endDate)) {
					expireStatus = "已到期";
				}

				// 版权信息:作品,出版社
				Copyrights copyrights = copyrightsService.findByCopyrightsNo(contractRights.getCopyrightsNo());
				if(!ObjectUtils.isEmpty(copyrights)) {
					String worksName = copyrights.getWorksName();
					String publishingName = copyrights.getPublishingName();
					contractRightsDto1.setWorksName(worksName);
					contractRightsDto1.setPublishingName(publishingName);
				}
				contractRightsDto1.setExpireStatus(expireStatus);
				contractRightsDtos.add(contractRightsDto1);
			}
			result.setContent(contractRightsDtos);
		}

		return result;
	}


	@ApiOperation(value="excel导出", notes="excel导出")
	@RequestMapping(value = "exportExcel.do", method = RequestMethod.GET)
	public void exportExcel(@ModelAttribute("contractRightsDto") ContractRightsDto contractRightsDto, HttpServletResponse response) {
		UserInfo userInfo = userInfoService.getById(CxtHolder.getUser().getUserId());
		if (UserTypeEnum.OP.getCode().equals(userInfo.getUserType())) {
			contractRightsDto.setCreateById(userInfo.getId());
		}
		Page page = getPageInfo();
		page.setCurrPage(1);
		page.setLimit(Integer.MAX_VALUE-1);
		PageInfo<ContractRightsDto> pageInfo = contractRightsService.pageDto(contractRightsDto,page);

		List<ContractRightsDto> list = pageInfo.getList();
		ArrayList<ContractRightsExportDto> contractRightsDtos = new ArrayList<>();
//		 修改人&过期状态set
		if (!CollectionUtils.isEmpty(list)) {
			for (ContractRightsDto contractRights : list) {
				Date now = new Date();
				Date endDate = contractRights.getEndDate();
				String expireStatus = null;
				int monthDiff = DateUtil.getMonthDiff( endDate,now);
				if (monthDiff == 0) {
					expireStatus = "1个月内到期";
				} else if (monthDiff > 0 && monthDiff < 3) {
					expireStatus = "3个月内到期";
				} else if (monthDiff >= 3 && monthDiff < 6) {
					expireStatus = "6个月内到期";
				} else if (monthDiff >= 6) {
					expireStatus = "6个月以外到期";
				}
				if (now.after(endDate)) {
					expireStatus = "已到期";
				}
				contractRights.setExpireStatus(expireStatus);
				ContractRightsExportDto exportDto = BeanCopyUtil.copy(contractRights, ContractRightsExportDto.class);
				contractRightsDtos.add(exportDto);

			}
		}
		//导出操作
		ExcelUtil.exportExcel(contractRightsDtos,"授权列表","授权列表",ContractRightsExportDto.class,DateUtil.toString(new Date(),DateUtil.yyyy_MM_dd)+ "授权列表.xls",response);
	}

    @ApiOperation(value="excel导入", notes="excel导入,模板下载路径(47.96.144.33:8080/授权导入模板.xlsx)")
	@PostMapping("importExcel.do")
	public Object importExcel(@RequestParam(value="file") MultipartFile file){
		List<ContractRightsImportDto> contractRightsImportDtos = ExcelUtil.importExcel(file, 11, 1, ContractRightsImportDto.class);
		List<ContractRightsDto> contractRightsDtos = BeanCopyUtil.copy(contractRightsImportDtos, ContractRightsDto.class);
		contractRightsService.doBatchAdd(contractRightsDtos);
		return ResultMessage.success();
	}
}
